package com.olddriver.crm.realm;

import com.olddriver.crm.domain.Employee;
import com.olddriver.crm.mapper.EmployeeMapper;
import com.olddriver.crm.mapper.PermissionMapper;
import com.olddriver.crm.mapper.RoleMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class MyRealm extends AuthorizingRealm {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RoleMapper roleMapper;

    /*认证*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        Object principal = token.getPrincipal();
        if (principal != null) {
            /*比对用户名,获取用户信息,并设置到info中*/
            Employee employee = employeeMapper.findEmpByUsername((String) principal);
            if (employee != null) {
                /*设置加密规则??在配置未见设置了这里是不是不需要了??*/
                SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(employee, employee.getPassword(), ByteSource.Util.bytes(employee.getUsername()), MyRealm.class.getName());
                return info;
            }
        }
        return null;
    }

    /*授权*/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        /*获取当前用户的身份信息*/
        Employee employee = (Employee) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        System.out.println("xxxxxxx");
        /*判断是否管理员*/
        if (employee.getAdmin()) {
            simpleAuthorizationInfo.addRole("admin");
            simpleAuthorizationInfo.addStringPermission("*:*");
        } else {
            // employee.getRoles()
            List<String> resourse = permissionMapper.findResourseByEmp(employee.getId());
            List<String> roleNames = roleMapper.findRoleNameByEmpId(employee.getId());
            simpleAuthorizationInfo.addStringPermissions(resourse);
            simpleAuthorizationInfo.addRoles(roleNames);
        }
        return simpleAuthorizationInfo;
    }
}
